#!/usr/bin/env python3
"""
Cython集成示例脚本

演示如何将Cython优化集成到现有的比对系统中
"""

import time
import numpy as np
from typing import List, Dict

def demo_cython_integration():
    """演示Cython集成的完整流程"""
    
    print("🚀 Cython比对逻辑集成演示")
    print("=" * 50)
    
    # 1. 检查Cython可用性
    print("\n1. 检查Cython可用性...")
    try:
        from cython_integration import get_cython_engine, check_cython_performance
        
        engine = get_cython_engine()
        print(f"✓ Cython引擎创建成功")
        print(f"  - Cython可用: {engine.is_available()}")
        print(f"  - 性能信息: {engine.get_performance_info()}")
        
    except ImportError:
        print("⚠ Cython模块未编译，请先运行: python build_cython.py")
        return
    
    # 2. 性能基准测试
    print("\n2. 性能基准测试...")
    test_sizes = [1000, 5000, 10000]
    
    for size in test_sizes:
        print(f"\n测试数据大小: {size} 字节")
        result = check_cython_performance(size)
        
        if result['cython_available']:
            cython_time = result['performance'].get('cython', {}).get('time', 'N/A')
            numpy_time = result['performance'].get('numpy', {}).get('time', 'N/A')
            speedup = result.get('speedup', 'N/A')
            
            print(f"  - NumPy时间: {numpy_time:.6f}秒")
            print(f"  - Cython时间: {cython_time:.6f}秒")
            print(f"  - 性能提升: {speedup}")
        else:
            print("  - Cython不可用，无法进行性能测试")
    
    # 3. 模拟帧数据创建
    print("\n3. 创建模拟帧数据...")
    frames1, frames2 = create_test_frames(num_frames=100, frame_size=1024)
    print(f"✓ 创建了{len(frames1)}个测试帧，每帧{frames1[0]['payload'].shape[0]}字节")
    
    # 4. 传统NumPy比对
    print("\n4. 传统NumPy比对...")
    start_time = time.time()
    numpy_result = compare_frames_numpy(frames1[:10], frames2[:10])
    numpy_time = time.time() - start_time
    print(f"✓ NumPy比对完成: {numpy_time:.4f}秒, 匹配帧数: {numpy_result['matching']}")
    
    # 5. Cython优化比对
    print("\n5. Cython优化比对...")
    if engine.is_available():
        start_time = time.time()
        cython_result = compare_frames_cython(frames1[:10], frames2[:10], engine)
        cython_time = time.time() - start_time
        speedup = numpy_time / cython_time if cython_time > 0 else 0
        
        print(f"✓ Cython比对完成: {cython_time:.4f}秒, 匹配帧数: {cython_result['matching']}")
        print(f"✓ 实际加速比: {speedup:.1f}x")
    else:
        print("⚠ Cython不可用，跳过优化比对")
    
    # 6. 批量处理演示
    print("\n6. 批量处理演示...")
    if engine.is_available():
        payloads1 = [frame['payload'] for frame in frames1[:20]]
        payloads2 = [frame['payload'] for frame in frames2[:20]]
        
        start_time = time.time()
        batch_results = engine.batch_compare_payloads(payloads1, payloads2)
        batch_time = time.time() - start_time
        
        matching_count = sum(batch_results)
        print(f"✓ 批量比对完成: {batch_time:.4f}秒")
        print(f"  - 总帧数: {len(batch_results)}")
        print(f"  - 匹配帧数: {matching_count}")
        print(f"  - 匹配率: {matching_count/len(batch_results)*100:.1f}%")
    
    # 7. 集成建议
    print("\n7. 集成到现有系统...")
    print("✓ 在现有比对函数中添加以下代码：")
    print_integration_code()
    
    print("\n🎉 Cython集成演示完成！")

def create_test_frames(num_frames: int, frame_size: int) -> tuple:
    """创建测试帧数据"""
    frames1 = []
    frames2 = []
    
    for i in range(num_frames):
        # 创建基础数据
        base_data = np.random.randint(0, 256, frame_size, dtype=np.uint8)
        
        # 第一个文件的帧
        frame1 = {
            'frame_count': i,
            'virtual_channel': i % 8,  # 8个虚拟信道
            'payload': base_data.copy(),
            'frame_format': '1024'
        }
        
        # 第二个文件的帧（大部分相同，少数不同）
        modified_data = base_data.copy()
        if i % 10 == 0:  # 10%的帧有差异
            # 添加一些随机差异
            diff_positions = np.random.choice(frame_size, size=5, replace=False)
            modified_data[diff_positions] = np.random.randint(0, 256, 5, dtype=np.uint8)
        
        frame2 = {
            'frame_count': i,
            'virtual_channel': i % 8,
            'payload': modified_data,
            'frame_format': '1024'
        }
        
        frames1.append(frame1)
        frames2.append(frame2)
    
    return frames1, frames2

def compare_frames_numpy(frames1: List[Dict], frames2: List[Dict]) -> Dict:
    """使用传统NumPy方法比对帧"""
    matching = 0
    total = min(len(frames1), len(frames2))
    
    for frame1, frame2 in zip(frames1, frames2):
        payload1 = frame1['payload']
        payload2 = frame2['payload']
        
        if np.array_equal(payload1, payload2):
            matching += 1
    
    return {
        'matching': matching,
        'total': total,
        'mismatch': total - matching
    }

def compare_frames_cython(frames1: List[Dict], frames2: List[Dict], engine) -> Dict:
    """使用Cython优化方法比对帧"""
    matching = 0
    total = min(len(frames1), len(frames2))
    
    for frame1, frame2 in zip(frames1, frames2):
        result = engine.compare_frames_detailed(frame1, frame2)
        
        if result.get('type') == 'matching':
            matching += 1
    
    return {
        'matching': matching,
        'total': total,
        'mismatch': total - matching
    }

def print_integration_code():
    """打印集成代码示例"""
    code = '''
# 在比对函数开头添加：
try:
    from cython_integration import get_cython_engine
    cython_engine = get_cython_engine()
    use_cython = cython_engine.is_available()
except ImportError:
    use_cython = False

# 在比对循环中：
if use_cython and len(frames1) > 100:  # 大数据使用Cython
    result = cython_engine.compare_frames_detailed(frame1, frame2, compare_range)
else:  # 小数据或Cython不可用时使用原有逻辑
    result = original_compare_function(frame1, frame2, compare_range)
'''
    
    print(code)

def demo_real_integration():
    """演示真实集成场景"""
    print("\n🔧 真实集成场景演示")
    print("-" * 30)
    
    try:
        from cython_integration import get_cython_engine
        
        # 模拟现有的比对函数
        def enhanced_compare_function(frames1, frames2, compare_range=None):
            """增强的比对函数，集成Cython优化"""
            
            # 尝试使用Cython引擎
            try:
                engine = get_cython_engine()
                if engine.is_available() and len(frames1) > 50:
                    print("✓ 使用Cython引擎进行高性能比对")
                    
                    # 使用Cython批量比对
                    payloads1 = [frame['payload'] for frame in frames1]
                    payloads2 = [frame['payload'] for frame in frames2]
                    
                    results = engine.batch_compare_payloads(payloads1, payloads2, compare_range)
                    matching_count = sum(results)
                    
                    return {
                        'method': 'cython',
                        'total_frames': len(results),
                        'matching_frames': matching_count,
                        'performance': 'optimized'
                    }
            except Exception as e:
                print(f"⚠ Cython引擎失败，回退到NumPy: {e}")
            
            # 备用NumPy实现
            print("✓ 使用NumPy备用实现")
            result = compare_frames_numpy(frames1, frames2)
            result['method'] = 'numpy'
            result['performance'] = 'standard'
            return result
        
        # 测试增强函数
        frames1, frames2 = create_test_frames(60, 512)
        result = enhanced_compare_function(frames1, frames2)
        
        print(f"✓ 比对方法: {result['method']}")
        print(f"✓ 性能模式: {result['performance']}")
        print(f"✓ 匹配结果: {result.get('matching_frames', result.get('matching'))} / {result.get('total_frames', result.get('total'))}")
        
    except ImportError:
        print("⚠ 请先编译Cython模块")

if __name__ == "__main__":
    # 运行完整演示
    demo_cython_integration()
    
    # 运行真实集成演示
    demo_real_integration()
    
    print("\n📖 更多信息请参考 README_Cython.md")
    print("🔧 编译Cython模块：python build_cython.py") 